<template>
  <div class="register">
    <img src="../assets/images/login_icon.png" alt="" />
    <input style="opacity: 0;position:absolute;width:0;height:0;" />
    <input type="password" style="opacity: 0;position:absolute;width:0;height:0;" />
    <div class="register_form" v-if="!isResetPwd">
      <div style="width: 100%;">
        <!-- 注册表单 -->
        <el-form ref="registerRef" :model="registerForm" :rules="registerRules" class="register-form">
          <div class="title">注册</div>
          <el-form-item prop="companyName" v-if="tenantEnabled">
            <div class="form_label">公司名称</div>
            <el-input v-model="registerForm.companyName" type="text" size="large" auto-complete="off" placeholder="请输入公司名称"> </el-input>
          </el-form-item>
          <el-form-item prop="industryName">
            <div class="form_label">行业</div>
            <el-select v-model="registerForm.industryName" filterable placeholder="请输入所属行业" style="width: 100%">
              <el-option v-for="item in industryList" :key="item.industryId" :label="item.industryName" :value="item.industryId"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="username">
            <div class="form_label">账号</div>
            <el-input v-model="registerForm.username" type="text" size="large" auto-complete="off" placeholder="请输入用于登录的账号"> </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <div class="form_label">密码</div>
            <el-input
              name="unique_user_name0"
              id="unique_user_id0"
              v-model="registerForm.password"
              :type="pwdInputType"
              size="large"
              auto-complete="new-password"
              placeholder="请输入不小于8位数的密码"
            >
              <template #suffix
                ><el-icon>
                  <Hide v-if="pwdInputType === 'password'" @click="togglePwdView" />
                  <View v-else @click="togglePwdView" />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="code">
            <div class="form_label">图形验证码</div>
            <div style="width: 100%;display: flex">
              <el-input v-model="registerForm.code" size="large" auto-complete="off" placeholder="验证码" style="flex: 1;">
                <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
              </el-input>
              <div class="login-code">
                <img :src="codeUrl" @click="getCode" class="login-code-img" />
              </div>
            </div>
          </el-form-item>
          <el-form-item prop="phonenumber">
            <div class="form_label">手机号码</div>
            <el-input
              v-model="registerForm.phonenumber"
              @blur="registerCheckPhoneFun($event)"
              size="large"
              auto-complete="off"
              placeholder="请输入手机号码"
            >
            </el-input>
          </el-form-item>
          <el-form-item prop="smsCode" v-if="captchaEnabled" style="position: relative;">
            <div class="form_label">短信验证码</div>
            <el-input size="large" v-model="registerForm.smsCode" auto-complete="off" placeholder="请输入验证码"> </el-input>
            <div>
              <div class="get_code_Btn" :style="cmpStyle" type="text" @click.stop="getSmsCode">
                {{ codeText }}
              </div>
            </div>
          </el-form-item>
          <el-form-item prop="invitationCode">
            <div class="form_label">邀请码<span>（选填）</span></div>
            <el-input v-model="registerForm.invitationCode" size="large" auto-complete="off" placeholder="请输入邀请码"> </el-input>
          </el-form-item>
          <el-form-item style="width:100%;">
            <el-button class="login_btn" :loading="loading" size="large" type="primary" @click.prevent="handleRegister">
              <span v-if="!loading">免费注册</span>
              <span v-else>注 册 中...</span>
            </el-button>
          </el-form-item>
        </el-form>
        <div class="rules_line">
          <div class="checked_border" @click="toggleIsArgee"><img v-if="isAgree" src="../assets/images/login_checked.png" alt="" /></div>
          <div @click="toggleIsArgee">
            请认真阅读并同意<span @click.stop="goRules('user')">《用户协议》</span><span @click.stop="goRules('private')">《隐私政策》</span>
          </div>
        </div>
      </div>
    </div>
    <!-- 重置表单 -->
    <div class="resetPwd_form" v-else>
      <el-form ref="resetPwdRef" :model="resetPwdForm" :rules="resetPwdRules" class="register-form">
        <div class="title">重置密码</div>
        <el-form-item prop="code">
          <div class="form_label">图形验证码</div>
          <div style="width: 100%;display: flex">
            <el-input v-model="resetPwdForm.code" size="large" auto-complete="off" placeholder="验证码" style="flex: 1;">
              <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
            </el-input>
            <div class="login-code">
              <img :src="codeUrl" @click="getCode" class="login-code-img" />
            </div>
          </div>
        </el-form-item>
        <el-form-item prop="phonenumber">
          <div class="form_label">手机号码</div>
          <el-input
            v-model="resetPwdForm.phonenumber"
            @blur="registerCheckPhoneFun($event)"
            type="text"
            size="large"
            auto-complete="off"
            placeholder="请输入手机号码"
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="smsCode">
          <div class="form_label">短信验证码</div>
          <el-input v-model="resetPwdForm.smsCode" type="text" size="large" auto-complete="off" placeholder="请输入验证码"> </el-input>
          <div>
            <div class="get_code_Btn" :style="cmpStyle" type="text" @click.stop="getSmsCode">
              {{ codeText }}
            </div>
          </div>
        </el-form-item>
        <el-form-item prop="newPwd">
          <div class="form_label">新密码</div>
          <el-input
            name="unique_user_name1"
            id="unique_user_id1"
            v-model="resetPwdForm.newPwd"
            :type="pwdInputType"
            size="large"
            auto-complete="new-password"
            placeholder="请输入新密码"
          >
            <template #suffix
              ><el-icon>
                <Hide v-if="pwdInputType === 'password'" @click="togglePwdView" />
                <View v-else @click="togglePwdView" />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="newPwdConfirm">
          <div class="form_label">再输一次</div>
          <el-input
            name="unique_user_name11"
            id="unique_user_id11"
            v-model="resetPwdForm.newPwdConfirm"
            :type="pwdInputTypeConfirm"
            size="large"
            auto-complete="off"
            placeholder="再次输入密码"
          >
            <template #suffix
              ><el-icon>
                <Hide v-if="pwdInputTypeConfirm === 'password'" @click="togglePwdView(0)" />
                <View v-else @click="togglePwdView(0)" />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item style="width:100%;">
          <el-button class="login_btn" :loading="loading" size="large" type="primary" @click.prevent="handleResetPwd">
            <span v-if="!loading">确认</span>
            <span v-else>重 置 中...</span>
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { listIndustry } from '@/api/logic/industry';
import { getCodeImg, register, getTenantList, forgetPassword, registerCheckPhone, sendAliyun, getAllTemplateIds } from '@/api/login';
import { updateUserPwd } from '@/api/user/index';
import { RegisterForm, TenantVO } from '@/api/types';
import useUserStore from '@/store/modules/user';
import useAppStore  from '@/store/modules/app';
import { to } from 'await-to-js';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const route = useRoute();
const router = useRouter();
const userStore = useUserStore()
const appStore = useAppStore();

// 是否是重置密码
const isResetPwd = ref(!!(route.query.resetPwd))
// 重置密码表单
const resetPwdForm = ref({
  phonenumber: '',
  code: '', // 图形验证码
  smsCode: '', // 短信验证码
  uuid: '',
  newPwd: '',
  newPwdConfirm: '',
})

// 新密码与确认密码是否一致
const isSame = ref(false)
// 确认新密码
const confirmNewPasswordValidator = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error("请再次输入密码"));
    isSame.value = false
  }
  if (resetPwdForm.value.newPwd !== value) {
    callback(new Error("两次输入的密码不一致"));
    isSame.value = false
  } else {
    isSame.value = true
    callback();
  }
}
// 重置密码表单校验规则
const resetPwdRules = {
  code: [{ required: true, trigger: 'blur', message: '请输入图形验证码' }],
  phonenumber: [{ required: true, trigger: 'blur', message: '请输入手机号码' }],
  smsCode: [{ required: true, trigger: 'blur', message: '请输入短信验证码' }],
  newPwd: [{ required: true, trigger: 'blur', message: '请输入新密码' }],
  newPwdConfirm: [{ required: true, trigger: 'blur', validator: confirmNewPasswordValidator }],
}
const resetPwdRef = ref()
// 调用接口重置
const handleResetPwd = () => {
  resetPwdRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      const [err] = await to(forgetPassword({
        password: resetPwdForm.value.newPwd,
        phone: resetPwdForm.value.phonenumber,
        code: resetPwdForm.value.code,
        uuid: resetPwdForm.value.uuid,
        smsCode: resetPwdForm.value.smsCode,
      }));
      if (!err) {
        await ElMessageBox.alert('重置成功', '系统提示', {
          dangerouslyUseHTMLString: true,
          type: 'success'
        });
        await router.push('/login');
      } else {
        loading.value = false;
      }
    }
  });
}
// 注册表单
const registerForm = ref({
  companyName: '', // 公司名称
  industryName: '', // 所属行业id
  username: '',
  password: '',
  phonenumber: '', // 手机号码
  code: '', // 图形验证码
  smsCode: '', // 短信验证码
  uuid: '',
  invitationCode: '', // 邀请码
});

// 租户开关
const tenantEnabled = ref(true);
// 注册表单校验规则
const registerRules: ElFormRules = {
  companyName: [{ required: true, trigger: 'blur', message: '请输入公司名称' }],
  industryName: [{ required: true, trigger: 'blur', message: '请输入所属行业' }],
  username: [
    { required: true, trigger: 'blur', message: '请输入用于登录的账号' },
    { min: 2, max: 20, message: '用户账号长度必须介于 2 和 20 之间', trigger: 'blur' }
  ],
  password: [
    { required: true, trigger: 'blur', message: '请输入不小于8位数的密码' },
    { min: 8, max: 20, message: '用户密码长度必须介于 8 和 20 之间', trigger: 'blur' }
  ],
  phonenumber: [
    { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, required: true, trigger: 'blur', message: '请输入正确的手机号码' },
  ],
  code: [{ required: true, trigger: 'change', message: '请输入图形验证码' }],
  smsCode: [{ required: true, trigger: 'change', message: '请输入短信验证码' }]
};
const loading = ref(false);
const captchaEnabled = ref(true);
const registerRef = ref<ElFormInstance>();
// 租户列表
// const tenantList = ref<TenantVO[]>([]);

// 行业列表
const industryList = ref([
  {
    industryId: '1',
    industryName: '行业列表'
  }
]);

// 获取行业下拉
const getListIndustry = async() => {
  const res = await listIndustry({isActive: 1});
  industryList.value = res.rows;
}

const pwdInputType = ref('password')
const pwdInputTypeConfirm = ref('password')
// 密码可见切换
const togglePwdView = (val) => {
  if (val) {
    if (pwdInputType.value === 'password') pwdInputType.value = 'text'
    else pwdInputType.value = 'password'
  } else {
    if (pwdInputTypeConfirm.value === 'password') pwdInputTypeConfirm.value = 'text'
    else pwdInputTypeConfirm.value = 'password'
  }
}


// 是否勾选同意协议
const isAgree = ref(false);

// 切换勾选协议
const toggleIsArgee = () => {
  isAgree.value = !isAgree.value;
};

// 跳转协议页面
const goRules = (cate: string) => {
  router.push(`/rules/${cate}`);
};
// 是否已发送验证码
const isSend = ref(false)
// 定时器获取验证码
const timer = ref(null)
// 倒计时
const countDown = ref(60)
// 验证码文字
const codeText = ref('立即获取')
// 模板id，阿里云发短信业务用
const templateId = ref('')
// 获取模板id
const getTemplateId = async () => {
  try {
    const res = await appStore.getTemplateId();
    templateId.value = res[isResetPwd.value ? '修改密码验证码' : '用户注册验证码']
  } catch(e) {
    console.log(e)
    templateId.value = ''
  }
}
// 获取手机验证码
const getSmsCode = async() => {
  const code = isResetPwd.value ? resetPwdForm.value.code : registerForm.value.code
  const phone = isResetPwd.value ? resetPwdForm.value.phonenumber : registerForm.value.phonenumber
  if (!code) return proxy?.$modal.msgError("请输入图形验证码");
  if (!/^1[3|4|5|6|7|8|9]\d{9}$/.test(phone)) return proxy?.$modal.msgError("请输入合法手机号");
  if (isRepeat.value) return proxy?.$modal.msgError("手机号已注册");
  if (isSend.value && timer.value) return
  try {
    const param = {
      phones: isResetPwd.value ? resetPwdForm.value.phonenumber : registerForm.value.phonenumber,
      templateId: templateId.value,
      code: isResetPwd.value ? resetPwdForm.value.code : registerForm.value.code,
      uuid: isResetPwd.value ? resetPwdForm.value.uuid : registerForm.value.uuid
    }
    await sendAliyun(param)
    isSend.value = true
    if (timer.value) clearInterval(timer.value)
    timer.value = setInterval(() => {
      countDown.value--
      codeText.value = `${countDown.value}s重新获取 `
      if (countDown.value === 0) {
        countDown.value = 60
        codeText.value = '重新获取'
        clearInterval(timer.value)
        timer.value = null
        isSend.value = false
      }
    }, 1000)
  } catch (error) {
    console.log(error);
    isSend.value = false
    if (timer.value) clearInterval(timer.value)
  }
}

/**
 * 获取图形验证码
 */
const cmpStyle = computed(() => {
  const code = isResetPwd.value ? resetPwdForm.value.code : registerForm.value.code
  const phone = isResetPwd.value ? resetPwdForm.value.phonenumber : registerForm.value.phonenumber
  if (!code || !phone) return { 'color': '#606266' }
  else return { 'color': countDown.value >= 60 ? '#096AFF' : '#606266' }
})
 const codeUrl = ref('');
 const getCode = async () => {
  const res = await getCodeImg();
  const { data } = res;
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
  if (captchaEnabled.value) {
    codeUrl.value = 'data:image/gif;base64,' + data.img;
    if (isResetPwd.value) resetPwdForm.value.uuid = data.uuid;
    else registerForm.value.uuid = data.uuid;

  }
};
// 手机号已重复注册
const isRepeat = ref(false)
// 校验手机号是否已被注册
const registerCheckPhoneFun = async(e) => {
  if (e.target.value) {
    try {
      isRepeat.value = await userStore.registerCheckPhoneFun(e.target.value)
    } catch (error) {
      console.log(error);
      isRepeat.value = true
    }
  }
}

// 注册方法
const handleRegister = () => {
  registerRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      const param = Object.assign({
        clientId: 'e5cd7e4891bf95d1d19206ce24a7b32e',
        grantType: 'password',
        tenantId: '000000',
        userType: 'sys_user'
      }, registerForm.value)
      const [err] = await to(register(param));
      if (!err) {
        const username = registerForm.value.username;
        await ElMessageBox.alert(username + ' 注册成功!', '系统提示', {
          dangerouslyUseHTMLString: true,
          type: 'success'
        });
        await router.push('/login');
      } else {
        loading.value = false;
      }
    }
  });
};

// const initTenantList = async () => {
//   const { data } = await getTenantList();
//   tenantEnabled.value = data.tenantEnabled === undefined ? true : data.tenantEnabled;
//   if (tenantEnabled.value) {
//     tenantList.value = data.voList;
//     if (tenantList.value != null && tenantList.value.length !== 0) {
//       registerForm.value.tenantId = tenantList.value[0].tenantId;
//     }
//   }
// };

onMounted(() => {
  getCode();
  getListIndustry()
  getTemplateId()
  // initTenantList();
});
onBeforeUnmount(() => {
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
})
</script>

<style lang="scss" scoped>
.register {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url('../assets/images/login_bg.jpg');
  background-size: cover;
  overflow: scroll;
  position: relative;
  font-size: 16px;
  & > img {
    width: 146px;
    height: auto;
    position: absolute;
    top: 22px;
    left: 32px;
  }
  .register_form, .resetPwd_form {
    position: absolute;
    top: 40px;
    left: 50%;
    transform: translateX(-50%);
    width: 41.66vw;
    // height: 92.59vh;
    padding: 38px 0 43px;
    margin: 40px auto 0;
    background: #ffffff;
    border-radius: 8px 8px 8px 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    .register-form {
      width: 384px;
      margin: 0 auto;
      box-sizing: border-box;
      .el-form-item {
        margin-bottom: 22px;
      }
      .title {
        height: 34px;
        line-height: 34px;
        font-weight: 500;
        font-size: 28px;
        color: #3d3d3d;
        text-align: center;
        margin-bottom: 16px;
      }
      .form_label {
        height: 24px;
        line-height: 24px;
        font-weight: 500;
        font-size: 18px;
        color: #3d3d3d;
        margin-bottom: 16px;
      }
      .get_code_Btn {
        position: absolute;
        right: 25px;
        bottom: 8px;
        padding: 0;
        font-weight: 400;
        font-size: 1.14rem;
        color: #096AFF;
        cursor: pointer;
      }
      .login_btn {
        font-size: 16px;
        margin-top: 16px;
        width: 384px;
        height: 64px;
        background-color: #096AFF;
        border-radius: 8px;
        text-align: center;
        line-height: 64px;
      }
    }
    .rules_line {
        height: 16px;
        margin-top: 45px;
        font-weight: 400;
        font-size: 1.14rem;
        color: #3d3d3d;
        display: flex;
        align-items: center;
        justify-content: center;
        .checked_border {
          width: 20px;
          height: 20px;
          border: 3px solid #D8D8D8;
          border-radius: 4px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 10px;
          img {
            width: 10px;
            height: 6px;
          }
        }
        span {
          color: #096aff;
        }
      }
  }
}
.resetPwd_form {
  padding-top: 203px!important;
  padding-bottom: 203px!important;
}
.register-form {
  background: #ffffff;
  .el-input {
    height: 48px;
    box-shadow: none!important;
    input {
      width: 384px;
      height: 48px;
      font-size: 16px !important;
    }
  }
}

:deep(.el-input__wrapper) {
    background: #F3F5F9 !important;
    border-radius: 8px 8px 8px 8px !important;
    border: none !important;
    height: 48px;
    box-shadow: none!important;
    padding-left: 24px;
    padding-right: 24px;
    input {
      font-size: 16px;
      background: #F3F5F9 !important;
    }
}
.login-code {
  width: 160px;
  height: 48px;
  margin-left: 10px;
  img {
    width: 100%;
    height: 100%;
  }
}
:deep(.el-input__inner::placeholder) {
  color:  #A8B0BC!important;
}
:deep(.el-input__suffix-inner) {
  font-size: 16px;
}
:deep(.el-input__prefix-inner) {
  font-size: 16px;
}
</style>
